package com.stylefeng.guns.modular.customer.controller;

import cn.afterturn.easypoi.entity.vo.NormalExcelConstants;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.baomidou.mybatisplus.plugins.Page;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.base.tips.SuccessTip;
import com.stylefeng.guns.core.common.annotion.Permission;
import com.stylefeng.guns.core.common.constant.Const;
import com.stylefeng.guns.core.common.constant.factory.ConstantFactory;
import com.stylefeng.guns.core.common.constant.factory.PageFactory;
import com.stylefeng.guns.core.common.exception.BizExceptionEnum;
import com.stylefeng.guns.core.datascope.DataScope;
import com.stylefeng.guns.core.exception.GunsException;
import com.stylefeng.guns.core.log.LogObjectHolder;
import com.stylefeng.guns.core.node.ZTreeNode;
import com.stylefeng.guns.core.shiro.ShiroKit;
import com.stylefeng.guns.core.support.BeanKit;
import com.stylefeng.guns.core.support.VlidationUtil;
import com.stylefeng.guns.modular.customer.dao.CustomerCompanyDao;
import com.stylefeng.guns.modular.customer.service.ICustomerCompanyManageService;
import com.stylefeng.guns.modular.customer.service.ICustomerCompanyService;
import com.stylefeng.guns.modular.customer.transfer.CustomerCompanyXlsM;
import com.stylefeng.guns.modular.customer.util.CustomerUtil;
import com.stylefeng.guns.modular.customer.warpper.CustomerCompanyWrapper;
import com.stylefeng.guns.modular.system.model.CustomerCompany;
import com.stylefeng.guns.modular.system.model.CustomerCompanyManage;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.flowable.bpmn.model.DataGrid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.naming.NoPermissionException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;


/**
 * 企业客户控制器
 *
 * @author fengshuonan
 * @Date 2018-04-02 11:42:14
 */
@Controller
@RequestMapping("/customerCompany")
public class CustomerCompanyController extends BaseController {

    private String PREFIX = "/customer/customerCompany/";

    @Autowired
    private ICustomerCompanyService customerCompanyService;

    @Autowired
    private ICustomerCompanyManageService customerCompanyManageService;

    @Autowired
    private CustomerCompanyDao customerCompanyDao;


    /**
     * 跳转到企业客户首页
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "customerCompany.html";
    }

    /**
     * 跳转到添加企业客户
     */
    @RequestMapping("/customerCompany_add")
    public String customerCompanyAdd() {
        return PREFIX + "customerCompany_add.html";
    }

    /**
     * 跳转到修改企业客户
     */
    @RequestMapping("/customerCompany_update/{customerCompanyId}")
    public String customerCompanyUpdate(@PathVariable Integer customerCompanyId, Model model) {
        CustomerCompany customerCompany = customerCompanyService.selectById(customerCompanyId);
        CustomerCompanyManage customerCompanyManage = customerCompanyManageService.selectById(customerCompanyId);
        model.addAttribute("item", customerCompany);
        model.addAttribute("items", customerCompanyManage);
        model.addAttribute("deptName", ConstantFactory.me().getDeptName(customerCompanyManage.getDepartId()));
        model.addAttribute("saleName", ConstantFactory.me().getUserNameById(customerCompanyManage.getSalesmanId()));
        Map<String, Object> map = BeanKit.beanToMap(customerCompany);
        model.addAttribute("item", new CustomerCompanyWrapper(map).warp());
        LogObjectHolder.me().set(customerCompany);
        LogObjectHolder.me().set(customerCompanyManage);
        return PREFIX + "customerCompany_edit.html";
    }

    /**
     * 获取企业客户列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(@RequestParam(value = "name", required = false) String name,
                       @RequestParam(value = "customerTypeCode", required = false) String customerTypeCode,
                       @RequestParam(value = "responsible", required = false) Integer responsible) {

        Page<CustomerCompany> page = new PageFactory<CustomerCompany>().defaultPage();

        List<Map<String, Object>> list;

        if (responsible != null && 1 == responsible) {
            list = customerCompanyDao.list(null, page, name, customerTypeCode, ShiroKit.getUser().getId());
        } else {
            list = customerCompanyDao.list(null, page, name, customerTypeCode, null);
        }
        page.setRecords((List<CustomerCompany>) new CustomerCompanyWrapper(list).warp());
        return super.packForBT(page);
    }


    @RequestMapping("/tree")
    @ResponseBody
    public List<ZTreeNode> tree() {
        if (ShiroKit.isAdmin()) {
            return this.customerCompanyDao.tree(null);
        } else {
            DataScope dataScope = new DataScope("id", CustomerUtil.getCustomerDataScope());
            return this.customerCompanyDao.tree(dataScope);
        }
    }

    @RequestMapping("/tree/all")
    @ResponseBody
    public List<ZTreeNode> treeAll() {
        return this.customerCompanyDao.tree(null);
    }


    /**
     * 新增企业客户
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    @Permission
    @ApiOperation(value = "新增企业客户", tags = "企业客户", httpMethod = "POST", code = 200, response = SuccessTip.class)
    @ApiImplicitParams(
            {
                    @ApiImplicitParam(name = "name", value = "名字", dataType = "string", required = true),
                    @ApiImplicitParam(name = "unifiedSocialCreditCode", value = "部门名称", dataType = "string", required = true),
                    @ApiImplicitParam(name = "shortName", value = "企业简称", dataType = "String", required = true),
                    @ApiImplicitParam(name = "legalPerson", value = "法定代表人", dataType = "string", required = true),
                    @ApiImplicitParam(name = "corporation", value = "所属集团（字典数据）", dataType = "string", required = true),
                    @ApiImplicitParam(name = "section", value = "所属板块", dataType = "string", required = true),
                    @ApiImplicitParam(name = "militaryCode", value = "军工代码", dataType = "string", required = true),
                    @ApiImplicitParam(name = "areaId", value = "所属区域（字典数据）", dataType = "Integer", required = true),
                    @ApiImplicitParam(name = "mainBusiness", value = "主营业务或产品", dataType = "string", required = false),
                    @ApiImplicitParam(name = "customerTypeCode", value = "客户类型（字典数据）", dataType = "String", required = true),
                    @ApiImplicitParam(name = "annualIncome", value = "年销售收入规模（万元）", dataType = "Integer", required = true),
                    @ApiImplicitParam(name = "annualPurchaseAmount", value = "年度采购规模", dataType = "Integer", required = true),
                    @ApiImplicitParam(name = "providerNum", value = "供应商数量", dataType = "Integer", required = true),
                    @ApiImplicitParam(name = "departId", value = "所属部门", dataType = "Integer", required = true),
                    @ApiImplicitParam(name = "salesmanId", value = "所属销售", dataType = "Integer", required = true),
                    @ApiImplicitParam(name = "source", value = "信息来源（字典数据）", dataType = "String", required = true),
                    @ApiImplicitParam(name = "isCcb", value = "是否建行账户（字典数据）", dataType = "String", required = true),
                    @ApiImplicitParam(name = "isPlanToOpenAccount", value = "是否计划开户（字典数据）", dataType = "String", required = true),
                    @ApiImplicitParam(name = "state", value = "当前状态", dataType = "Integer", required = false)
            }
    )
    public Object add(@Validated CustomerCompany customerCompany, @Validated CustomerCompanyManage customerCompanyManage) {
        customerCompanyService.insert(customerCompany, customerCompanyManage);
        return SUCCESS_TIP;
    }

    /**
     * 删除企业客户
     */
    @Permission(Const.ADMIN_NAME)
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestParam Integer customerCompanyId) {
        customerCompanyService.deleteById(customerCompanyId);
        return SUCCESS_TIP;
    }

    /**
     * 修改企业客户
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    @Permission
    @ApiOperation(value = "修改企业客户", tags = "企业客户", httpMethod = "POST", code = 200, response = SuccessTip.class)
    @ApiImplicitParams(
            {
                    @ApiImplicitParam(name = "id", value = "id", dataType = "Integer", required = true),
                    @ApiImplicitParam(name = "name", value = "名字", dataType = "string", required = true),
                    @ApiImplicitParam(name = "unifiedSocialCreditCode", value = "部门名称", dataType = "string", required = true),
                    @ApiImplicitParam(name = "shortName", value = "企业简称", dataType = "String", required = true),
                    @ApiImplicitParam(name = "legalPerson", value = "法定代表人", dataType = "string", required = true),
                    @ApiImplicitParam(name = "corporation", value = "所属集团（字典数据）", dataType = "string", required = true),
                    @ApiImplicitParam(name = "section", value = "所属板块", dataType = "string", required = true),
                    @ApiImplicitParam(name = "militaryCode", value = "军工代码", dataType = "string", required = true),
                    @ApiImplicitParam(name = "areaId", value = "所属区域（字典数据）", dataType = "Integer", required = true),
                    @ApiImplicitParam(name = "mainBusiness", value = "主营业务或产品", dataType = "string", required = false),
                    @ApiImplicitParam(name = "customerTypeCode", value = "客户类型（字典数据）", dataType = "String", required = true),
                    @ApiImplicitParam(name = "annualIncome", value = "年销售收入规模（万元）", dataType = "Integer", required = true),
                    @ApiImplicitParam(name = "annualPurchaseAmount", value = "年度采购规模", dataType = "Integer", required = true),
                    @ApiImplicitParam(name = "providerNum", value = "供应商数量", dataType = "Integer", required = true),
                    @ApiImplicitParam(name = "departId", value = "所属部门", dataType = "Integer", required = true),
                    @ApiImplicitParam(name = "salesmanId", value = "所属销售", dataType = "Integer", required = true),
                    @ApiImplicitParam(name = "source", value = "信息来源（字典数据）", dataType = "String", required = true),
                    @ApiImplicitParam(name = "isCcb", value = "是否建行账户（字典数据）", dataType = "String", required = true),
                    @ApiImplicitParam(name = "isPlanToOpenAccount", value = "是否计划开户（字典数据）", dataType = "String", required = true),
                    @ApiImplicitParam(name = "state", value = "当前状态", dataType = "Integer", required = false)
            }
    )
    public Object update(@Validated CustomerCompany customerCompany, @Validated CustomerCompanyManage customerCompanyManage) throws NoPermissionException {
        if(!CustomerUtil.validEditPermission(customerCompany.getId())){
            throw new NoPermissionException();
        };
        customerCompanyService.updateById(customerCompany);
        customerCompanyManageService.updateById(customerCompanyManage);
        return SUCCESS_TIP;
    }

    @RequestMapping(value = "/update/customerCompany")
    @ResponseBody
    public Object updateCustomerCompany(@Validated CustomerCompany customerCompany) throws NoPermissionException {
        if(!CustomerUtil.validEditPermission(customerCompany.getId())){
            throw new NoPermissionException();
        };
        customerCompanyService.updateById(customerCompany);
        return SUCCESS_TIP;
    }

    @RequestMapping(value = "/customerCompany_detail/{customerCompanyId}")
    public Object toDetail(@PathVariable("customerCompanyId") Integer customerCompanyId, Model model) {
        Map map = (Map) this.detail(customerCompanyId);
        model.addAttribute("item", map);
        return PREFIX + "customerCompany_detail.html";
    }


    /**
     * 企业客户详情
     */
    @RequestMapping(value = "/detail/{customerCompanyId}")
    @ResponseBody
    public Object detail(@PathVariable("customerCompanyId") Integer customerCompanyId) {
        CustomerCompany customerCompany = customerCompanyService.selectById(customerCompanyId);

        if (customerCompany == null) {
            throw new GunsException(BizExceptionEnum.DB_RESOURCE_NULL);
        }
        Map<String, Object> map = BeanKit.beanToMap(customerCompany);
        CustomerUtil.putAuthority(map, customerCompany.getId());
        return new CustomerCompanyWrapper(map).warp();
    }


    /**
     * 导出Excel模板
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/exportXlsByM", headers = {"Accept=application/vnd.ms-excel"})
    public String exportXlsByT(HttpServletRequest request, HttpServletResponse response
            , DataGrid dataGrid, ModelMap modelMap) {
        modelMap.put(NormalExcelConstants.FILE_NAME, "客户模板");
        modelMap.put(NormalExcelConstants.CLASS, CustomerCompanyXlsM.class);
        modelMap.put(NormalExcelConstants.PARAMS, new ExportParams("客户列表",
                "导出信息"));
        modelMap.put(NormalExcelConstants.DATA_LIST, CustomerCompanyXlsM.example());
        return NormalExcelConstants.EASYPOI_EXCEL_VIEW;//View名称
    }


    @RequestMapping(method = RequestMethod.POST, path = "/importExcel")
    @ResponseBody
    public Object importExcel(MultipartHttpServletRequest multipartRequest, HttpServletResponse response) throws Exception {
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            //标题行数
            params.setTitleRows(1);
            //表头行数
            params.setHeadRows(1);
            //是否需要保存上传的Excel
            params.setNeedSave(false);
            List<CustomerCompanyXlsM> result = ExcelImportUtil.importExcel(file.getInputStream(), CustomerCompanyXlsM.class, params);
            VlidationUtil.validateList(result);
            customerCompanyService.insertXlsList(result);
        }
        return "文件导入成功";
    }

}





